package tech.senri.iot.socket.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.listener.PatternTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter
import tech.senri.iot.socket.service.MessageHandleService
import java.util.concurrent.CountDownLatch


@Configuration
class RedisMQConfig
{
    @Bean
    fun container(connectionFactory: RedisConnectionFactory,
                  responseMessageListenerAdapter: MessageListenerAdapter,
                  requestMessageListenerAdapter: MessageListenerAdapter): RedisMessageListenerContainer
    {
        val container = RedisMessageListenerContainer()
        container.setConnectionFactory(connectionFactory)
        container.addMessageListener(responseMessageListenerAdapter, PatternTopic(device_message_response))
        container.addMessageListener(requestMessageListenerAdapter, PatternTopic(device_message_request))
        return container
    }

    @Bean
    fun responseMessageListenerAdapter(receiver: MessageHandleService): MessageListenerAdapter
    {
        return MessageListenerAdapter(receiver)
    }

    @Bean
    fun requestMessageListenerAdapter(receiver: MessageHandleService): MessageListenerAdapter
    {
        return MessageListenerAdapter(receiver, "handleRequestMessage")
    }

    @Bean
    fun latch(): CountDownLatch
    {
        return CountDownLatch(1)
    }

    @Bean
    fun template(connectionFactory: RedisConnectionFactory): StringRedisTemplate
    {
        return StringRedisTemplate(connectionFactory)
    }

    companion object
    {
        /**
         * 设备状态数据上报
         */
        const val device_message_response = "device.message.response"
        const val device_message_request = "device.message.request"
    }
}
